import Vue 						from 'vue'
import util 					from '../../util'
import axios 					from 'axios'
import { List,Toast,Dialog } 	from 'vant'
Vue.use(List,Toast,Dialog);
let timer = null;

import sharImg 					from '../../static/images/invite-bao2.png';
import defaultHeaderImg 		from '../../static/images/partner_default_img.png';

export default {
	name: 'invite',
	data(){
		return {
			wait:false,
			headImg:window.localStorage.getItem('headImg') || '',			//头像
			accountName:window.localStorage.getItem('accountName') || '',	//用户名
			uid:window.localStorage.getItem('uid') || '',
			moneyRate:'--',		//返佣比例
			leftMoney:'--',		//余额
			inviteCode:'',		//我的邀请码
			isSuperPartner:window.localStorage.getItem('isSuperPartner')?Number(window.localStorage.getItem('isSuperPartner')):0,	//是否超级合伙人
			subFriends:'',		//直接返佣人数
			subAgent:'',		//间接返佣人数

			list:[],
			loading:false,
			finished:false,
			loadError:false,

			currentId:'USDT',		//当前币种

			langDialog:false,		//是否显示语言选择弹窗
			inviteLocale:'',		//推广链接邀请语言
			getInviteUrl2:'',
			isShowNav:true,			//是否隐藏顶部导航
			eyeOpen:false,		    //返佣比例是否可见
			activeId:1,				//活跃高亮tab ID
			manageDialog:false,
			manageDialogType:0,		//弹窗类型  1:管理   2:备注
			manageLevel:[
                {type:2,level:'',selected:true,shown:true},
                {type:3,level:'',selected:false,shown:true},
                {type:4,level:'',selected:false,shown:true}
            ],
            manageUid:'',                          //编辑的用户uid
            manageRateE2:'',                       //下级返佣比例
            manageRemark:'',					   //备注
			pageIndex:1,
			debug:1,
			searchUID:'',			//搜索UID
			searchUID2:'',			//搜索UID
			searchList:[],		 	//搜索结果
			btnLoading:false,		//按钮是否加载中
			showTime:false,			//是否显示时间筛选弹窗
			defaultDate:[],			//默认日期
			listIndex:[],			//新版“返佣概览”
			total:{},				//“返佣概览”总数
			distance:0,
			distanceTop:0,
			selectColumns:0,		//选中的时间筛选
			listLen:0,
			rebateNavId:1,
			rebateList1:[],			//返佣明细(返佣记录)
			rebateList1Num:0,		//返佣明细(返佣记录)总数
			rebateList2:[],			//返佣明细(待审核记录)
			rebateList2Num:0,		//返佣明细(待审核记录)总数
			loading2:false,
			finished2:false,
			loadError2:false,
			level1RegCountToday:'', //今日注册
			inOutId:1,				//出入金记录ID
			listIn:[],				//入金记录
			listOut:[],				//出金记录
			distance2:0,
			distanceTop2:0,
			inOutLoading:false,		//出入金是否加载中
		}
	},
	computed:{
		themeIndexColor(){
			return this.themeIndex==1?'#ffffff':'#171A1F'
		},
		shownLeftMoney(){
			return util.intercept(this.leftMoney,this.currentId==='USDT'?2:8)
		},
		rebateList(){
			let _arr = this.rebateNavId===1?this.rebateList1:this.rebateList2;
			return _arr.slice(0,7)
		},
		newTab(){
			let _arr = [
				{id:1,name:this.$t('invite-key43'),selected:false,shown:true},
				{id:2,name:this.$t('invite-new40'),selected:false,shown:true},
				{id:3,name:this.$t('invite-new17'),selected:false,shown:true},
				{id:4,name:this.$t('invite-new41'),selected:false,shown:true},
				{id:5,name:this.$t('partnerNew04'),selected:false,shown:this.locale==='zh'?true:false},
			];
			_arr.map(item => {
				item.selected = item.id == this.activeId?true:false
			})
			return this.isSuperPartner===0?_arr.filter(item => item.id>2).reverse():_arr
		},
		getInviteUrl(){
			let _host = '';
			if(util.status === 2){
				_host = 'https://uat-h5.deepcoin.me'
			}else if(util.status === 3){
				_host = 'https://pre-h5.deepcoin.me'
			}else{
				_host = 'https://net-h5.deepcoin.info'
			}
			return _host+'/activity/invite/index.html?inviteId='+ this.inviteCode +'&lang='+this.inviteLocale
		},
		showMoneyRate(){
			return this.eyeOpen?(Number(this.moneyRate) >= 85?85:this.moneyRate)+'%':'****'
		},
		iconList(){
			return [
				{ name:'USDT',color:this.currentId === 'USDT'?'#0080FF':''},
				{ name:'BTC',color:this.currentId === 'BTC'?'#0080FF':''}
			]
		},
		countrys(){
			return [
				{ name: '中文简体',code:'zh', color: this.inviteLocale === 'zh'?'#0080FF':''},
        		{ name: '日本語', code:'ja', color: this.inviteLocale === 'ja'?'#0080FF':''},
        		{ name: 'English',code:'en', color: this.inviteLocale === 'en'?'#0080FF':''},
			]
		},
		contractListNew(){
            return [
                {id:-1,name:this.$t('friends-key1'),type:'',},               // 全部
                {id:1,name:this.$t('rebatelist1'),type:'SwapU',},            // U本位合约
                {id:2,name:this.$t('navMenu2'),type:'Swap',},                // 币本位合约
                {id:3,name:this.$t('apinav54'),type:'Spot',},                // 现货
                {id:4,name:this.$t('rebatelist2'),type:'CFD',},              // 差价合约-订单模式
                {id:5,name:this.$t('rebatelist3'),type:'CFDCross',},         // 差价合约-全仓模式
                {id:6,name:this.$t('rebatelist4'),type:'Guess',},            // 猜涨跌
				{id:7,name:this.$t('backList-nav'),type:'CFDSP',}            // 闪电合约-逐仓模式
            ]
        },
        columns(){
			let _arr = [this.$t('backList-key10'),this.$t('backList-key11'),this.$t('backList-key12'),this.$t('invite-new28'),this.$t('invite-new29')];
			return _arr
		},
		webUrl(){
			return this.locale === 'zh'?'https://www.deepcoin.in':'https://www.deepcoin.com'
		},
		rebateMenus(){
			let _arr = [
				{
					id:1,
					name: this.$t('invite-key17'),
					num:this.rebateList1Num,
					selected:true,
					shown:true
				},
				{
					id:2,
					name: this.$t('invite-new25'),
					num:this.rebateList2Num,
					selected:false,
					shown:this.locale==='zh'?true:false
				}
			];
			_arr.map(item => {
				item.selected = item.id === this.rebateNavId?true:false
			})
			return _arr
		},
		inOutMenus(){
			let _arr = [
				{
					id:1,
					name: this.$t('partnerNew05'),
					selected:true,
					shown:true
				},
				{
					id:2,
					name: this.$t('partnerNew06'),
					selected:false,
					shown:true
				}
			];
			_arr.map(item => {
				item.selected = item.id === this.inOutId?true:false
			})
			return _arr
		},
		listInOut(){
			return this.inOutId == 1?this.listIn:this.listOut;
		},
		sharImg(){
			return sharImg
		}
	},
	watch:{
		activeId:{
			handler(n,o){
				let scroll = this.$refs.bdScroll;
				if(scroll && this.locale === 'zh' && this.isSuperPartner == 1){
					scroll.scrollLeft = n < 3?0:50;
				}
				if(n == 2){
					this.getRebateLog(1);
					this.getRebateLog(2);
				}
				if(n == 3 && this.searchList.length===0) this.goSearch();
				if(n == 4) this.createInviteCode();
				if(n == 5) this.moneyLog(this.inOutId==1?'in':'out');
			},
			immediate:true
		},
		rebateNavId(n,o){
			if(n != o) {
				this.getRebateLog(1);
				this.getRebateLog(2);
			}
		},
		inOutId(n,o){
			if(this.activeId != 5) return
			if(n != o){
				this.moneyLog(n==1?'in':'out')
			}
		}
	},
	methods:{
		searchFromBtn(){
			// this.searchUID2 = '';
			this.listIn = this.listOut = [];
			this.moneyLog(this.inOutId==1?'in':'out');
		},
		moneyLog(type){
			//出入金记录
			if(this.inOutLoading) return
			this.inOutLoading = true;
			util.fetch2(`${util.ajaxUrl2}/api/v1/user/money-log`,{
				uid: this.searchUID2 || '',
				start: '',
				end: '',
				type: type,
				page: 1,
				size: 10
			}).then(res => {
               	if(res && res.code === 0 && res.data && res.data.list){
               		// res.data.list = []
               		res.data.list.map(item => {
               			let arrTime = util.transTime4(item.time);
               			item.time = arrTime[0]+'/'+arrTime[1]+'/'+ arrTime[2] +' '+arrTime[3]+':'+arrTime[4]+':'+arrTime[5];
		                //入金方式
		                switch (item.type) {
		                    case (1):
		                        item.typeShown = '支付宝';
		                        break;
		                    case (2):
		                        item.typeShown = '银行卡';
		                        break;
		                    case (3):
		                        item.typeShown = '钱包';
		                        break;
		                    case (4):
		                        item.typeShown = '微信';
		                        break;
		                    default:
		                        item.typeShown = '--';
		                        break;
		                }
		                if(type == 'in'){
			                //入金状态
			                switch (item.state) {
			                    case (1):
			                        item.stateShown = '等待付款';
			                        break;
			                    case (2):
			                        item.stateShown = '等待确认';
			                        break;
			                    case (3):
			                        item.stateShown = '充值成功';
			                        break;
			                    case (4):
			                        item.stateShown = '区块确认中';
			                        break;
			                    case (-99):
			                        item.stateShown = '撤销充值';
			                        break;
			                    case (99):
			                        item.stateShown = '驳回充值';
			                        break;
			                    default:
			                        item.stateShown = '--';
			                        break;
			                }
		                }else{
			                //出金状态
		                    switch (item.state) {
		                        case (-1):
		                            item.stateShown = '审核通过';
		                            break;
		                        case (-2):
		                            item.stateShown = '提交审核';
		                            break;
		                        case (-3):
		                            item.stateShown = '审核不通过';
		                            break;
		                        case (-4):
		                            item.stateShown = '区块确认中';
		                            break;
		                        case (-5):
		                            item.stateShown = '订单提交成功';
		                            break;
		                        case (-99):
		                            item.stateShown = '失败';
		                            break;
		                        case (99):
		                            item.stateShown = '成功';
		                            break;
		                        default:
		                            item.stateShown = '--';
		                            break;
		                    }
	                    }
		                item.history_in = util.countNum(item.history_in,item.currency==='USDT'?2:8);
		                item.history_out = util.countNum(item.history_out,item.currency==='USDT'?2:8);
		                item.money = util.countNum(item.money,item.currency==='USDT'?2:8);
               		})
                    if(type==='in') this.listIn = res.data.list;
                    if(type==='out') this.listOut = res.data.list;
                }else{
                	Toast(this.errMsg.find(item => item.code === res.code)?this.errMsg.find(item => item.code === res.code)[this.locale]:res.msg || this.$t('noError'))
                }
                this.$nextTick(() => {
                	if(this.$refs && this.$refs.scrollInOut){
						this.$refs.scrollInOut.onscroll = res => {
							this.distance2 = res.target.scrollLeft;
							this.distanceTop2 = res.target.scrollTop;
						}
					}
                });
			}).catch(e => {
				window.updateError('money-log:'+window.localStorage.getItem('uid'))
				console.log(e)
			}).finally(e => {
				this.inOutLoading = false;
			})
		},
		jumpToDetail(num,type,date){
			//跳转到详情
			if(num <= 0) return
			this.$router.push('/inviteDetail?pageState='+type+'&date='+date)
		},
		openDebug(){
			this.debug++;
			if(this.debug > 10){
				window.localStorage.setItem('dialogDebug','1')
			}
		},
		showAmountInEn(){
			if(this.locale != 'en') return
			Dialog.confirm({
				title: '',
				message: 'Including referrals <br />of all sub-affiliates.',
				className:'fullDialog-toast'+(this.themeIndex==1?' dialog-dark':''),
				confirmButtonText: this.$t('invite-new27'),
				showCancelButton:false,
				confirmButtonColor:'#1A76FF',
			}).then(() => {
				console.log('confirm')
			}).catch(() => {
				console.log('cancel')
			})
		},
		showTimeDesc(){
			Dialog.confirm({
				title: '',
				message: this.$t('invite-new26'),
				className:'fullDialog-toast'+(this.themeIndex==1?' dialog-dark':''),
				confirmButtonText: this.$t('invite-new27'),
				showCancelButton:false,
				confirmButtonColor:'#1A76FF',
			}).then(() => {
				console.log('confirm')
			}).catch(() => {
				console.log('cancel')
			})
		},
		getRebateLog(rebateNavId=this.rebateNavId){
			//返佣明细
			this.loading2 = true;
			// this.rebateList = [];
			this.finished2 = false;
			this.loadError2 = false;
			let _url = util.ajaxUrl2+'/api/v1/user/'+(rebateNavId==1?'rebate-log':'black-log');
			util.fetch2(_url,{
				page: 1,
				size: 10,
				product_group: '',
				search: '',
				start: '',
				end: ''
			}).then(res => {
               	if(res && res.code === 0){
                    if(res.data && res.data.list){
                    	if(res.data.list.length){
	                    	res.data.list.map(item => {
		                        item.day2 = util.transTime3(item.order_time);
		                        item.rebate = util.countNum(item.rebate,item.currency==='USDT'?2:8);
		                        //交易类型
		                        item.productName = '';
		                        let _findType = this.contractListNew.find(ele => ele.type === item.product_group);
		                        if(_findType){
		                            item.productName = _findType.name;
		                        }
		                    })
	                    }
	                    if(rebateNavId == 1){
	                    	this.rebateList1 = res.data.list;
	                    	this.rebateList1Num = res.data.total;
	                    }else{
	                    	this.rebateList2 = res.data.list;
	                    	this.rebateList2Num = res.data.total;
	                    }
                    	// if(rebateNavId === this.rebateNavId) this.rebateList = res.data.list;
                    	// if(this.rebateList.length > 7) this.rebateList.length = 7;
                    	this.loadError2 = false;
                    }else{
                    	this.rebateList = [];
                    	this.loadError2 = true;
                    }
                }else{
                	Toast(this.errMsg.find(item => item.code === res.code)?this.errMsg.find(item => item.code === res.code)[this.locale]:res.msg || this.$t('noError'))
                }
                this.loading2 = false;
                this.finished2 = true;
			}).catch(e => {
				window.updateError(_url+window.localStorage.getItem('uid'))
				Toast(this.dialogSystemErr);
			})
		},
		inputBlur(){
			setTimeout(()=>{
				window.scrollTo(0, 0);
			},100)
		},
		onConfirm(e){
			//点击确定
			this.ctrlShown();
			if(window.selectColumns != this.selectColumns){
				this.selectColumns = window.selectColumns;
				//判断时间
				let _end = +new Date();
				let start = '',end = '';
				let target = this.columns[this.selectColumns];
				// 今日 || 昨日
				if(target == this.$t('backList-key11') || target == this.$t('backList-key12')){
					// 昨日
					if(target == this.$t('backList-key12')) _end = _end - 24*60*60*1000;
					let endYear     = new Date(_end).getFullYear();
				    let endMonth    = new Date(_end).getMonth() + 1;
				    let endDate     = new Date(_end).getDate();
				    endMonth = endMonth.toString().length===1?'0'+endMonth:endMonth;
				    endDate  = endDate.toString().length===1?'0'+endDate:endDate;

					start = endYear+'-'+endMonth+'-'+endDate;
					end   = endYear+'-'+endMonth+'-'+endDate;
				}else if(target == this.$t('backList-key10') || target == this.$t('invite-new28')){
					// 全部时间 || 本周
					//初始化默认日期
					let min = target == this.$t('backList-key10')?7:new Date(_end).getDay()-1;
					let _start = +new Date() - min*24*60*60*1000;

					let startYear     = new Date(_start).getFullYear();
				    let startMonth    = new Date(_start).getMonth() + 1;
				    let startDate     = new Date(_start).getDate();
				    startMonth = startMonth.toString().length===1?'0'+startMonth:startMonth;
				    startDate  = startDate.toString().length===1?'0'+startDate:startDate;

					let endYear     = new Date(_end).getFullYear();
				    let endMonth    = new Date(_end).getMonth() + 1;
				    let endDate     = new Date(_end).getDate();
				    endMonth = endMonth.toString().length===1?'0'+endMonth:endMonth;
				    endDate  = endDate.toString().length===1?'0'+endDate:endDate;

				    //本周
					start = target == this.$t('invite-new28')?startYear+'-'+startMonth+'-'+startDate:'';
					end = endYear+'-'+endMonth+'-'+endDate;
				}else if(target == this.$t('invite-new29')){
					//初始化默认日期
					let _start = +new Date() - 29*24*60*60*1000;

					let startYear     = new Date(_start).getFullYear();
				    let startMonth    = new Date(_start).getMonth() + 1;
				    let startDate     = new Date(_start).getDate();
				    startMonth = startMonth.toString().length===1?'0'+startMonth:startMonth;
				    startDate  = startDate.toString().length===1?'0'+startDate:startDate;

					let endYear     = new Date(_end).getFullYear();
				    let endMonth    = new Date(_end).getMonth() + 1;
				    let endDate     = new Date(_end).getDate();
				    endMonth = endMonth.toString().length===1?'0'+endMonth:endMonth;
				    endDate  = endDate.toString().length===1?'0'+endDate:endDate;

					start = startYear+'-'+startMonth+'-'+startDate;
					end = endYear+'-'+endMonth+'-'+endDate;
				}
				this.sketchList(start,end,2)
			}
		},
		onChange(picker, value, index) {
			//拖动选择停止的时候保存数据
			window.selectColumns = index;
    	},
		ctrlShown(){
			//控制弹窗是否显示
			this.showTime = !this.showTime
		},
		sketchList(start,end,type){
			if(!start || !end){
				//初始化默认日期
				let _end = +new Date();
				let _start = +new Date() - 9*24*60*60*1000;

				let startYear     = new Date(_start).getFullYear();
			    let startMonth    = new Date(_start).getMonth() + 1;
			    let startDate     = new Date(_start).getDate();
			    startMonth = startMonth.toString().length===1?'0'+startMonth:startMonth;
			    startDate  = startDate.toString().length===1?'0'+startDate:startDate;

				let endYear     = new Date(_end).getFullYear();
			    let endMonth    = new Date(_end).getMonth() + 1;
			    let endDate     = new Date(_end).getDate();
			    endMonth = endMonth.toString().length===1?'0'+endMonth:endMonth;
			    endDate  = endDate.toString().length===1?'0'+endDate:endDate;

				start = startYear+'-'+startMonth+'-'+startDate;
				end = endYear+'-'+endMonth+'-'+endDate;
			}
			this.total = {};
			this.listIndex = [];
			this.loading2 = true;
			this.finished2 = false;
			this.loadError2 = false;
			window['selectColumns'] = this.selectColumns;
			util.fetch2(`${util.ajaxUrl2}/api/v1/index/sketch-list`,{
				currency: this.currentId,
				start: start,
				end: end,
			}).then(res => {
               	if(res && res.code === 0){
                    let _total = {};
                    // 本周
                	if(this.columns[this.selectColumns].includes(this.$t('friends-key1'))){
                		_total = res.data.total;
                	}else{
                		_total = res.data.total_day;
                	}
                	_total.amount_in = util.countNum(_total.amount_in,this.currentId=='USDT'?2:8);
                    _total.trade = util.countNum(_total.trade,this.currentId=='USDT'?2:8);
                    _total.fee = util.countNum(_total.fee,this.currentId=='USDT'?2:8);
                    _total.rebate = util.countNum(_total.rebate,this.currentId=='USDT'?2:8);
                    _total.amount_out = util.countNum(_total.amount_out,this.currentId=='USDT'?2:8);
                    this.total = _total;
                    //列表
                    res.data.list.reverse();
                    this.listLen = res.data.list.length;
                    res.data.list.map((item,index) => {
                    	if(index < 10 && this.selectColumns===0 || this.selectColumns > 0){
	                        item.amount_in = util.countNum(item.amount_in,this.currentId=='USDT'?2:8);
	                        item.amount_out = util.countNum(item.amount_out,this.currentId=='USDT'?2:8);
	                        item.trade = util.countNum(item.trade,this.currentId=='USDT'?2:8);
	                        item.fee = util.countNum(item.fee,this.currentId=='USDT'?2:8);
	                        item.rebate = util.countNum(item.rebate,this.currentId=='USDT'?2:8);
	                        // item.num_trade = 10;
	                        this.listIndex.push(item)
                        }
                    })
					this.finished2 = true;
					this.loadError2 = false;
                }else{
					this.finished2 = true;
					this.loadError2 = true;
                	Toast(this.errMsg.find(item => item.code === res.code)?this.errMsg.find(item => item.code === res.code)[this.locale]:res.msg || this.$t('noError'))
                }
                this.loading2 = false;
			}).catch(e => {
				Toast(this.dialogSystemErr);
				this.loading2 = false;
				this.finished2 = true;
				this.loadError2 = true;
				window.updateError('sketch-list:'+window.localStorage.getItem('uid'))
            	// throw new Error('timeout+"'+ err.config.url +'",uid:'+window.localStorage.getItem('uid'));

			})
		},
		submitRemark(){
			//修改备注
			this.btnLoading = true;
			this.manageDialog = true;
			//校验表情符号
			let reg = /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g;
			if(reg.test(this.manageRemark)){
				Toast(this.$t('invite-new30'));
				return
			}
			util.fetch2(`${util.ajaxUrl2}/api/v1/user/agent-remark`,{
				remark:this.manageRemark,
                uid:this.manageUid
			}).then(res => {
               	Toast(res.code === 0?this.$t('invite-new31'):this.errMsg.find(item => item.code === res.code)?this.errMsg.find(item => item.code === res.code)[this.locale]:res.msg || this.$t('noError'))
				this.btnLoading = false;
				this.manageDialog = false;
				if(res && res.code === 0){
					//若备注成功，则更新备注内容
					let find = this.searchList.find(item => item.uid === this.manageUid);
					find.remark = this.manageRemark;
				}
			}).catch(e => {
				window.updateError('agent-remark:'+window.localStorage.getItem('uid'))
				Toast(this.dialogSystemErr);
			})
		},
		submitManage(){
            //修改返佣比例
            if(!this.manageRateE2){
                Toast(this.$t('invite-new32'))
                return
            }
            this.btnLoading = true;
            let selectItem = this.manageLevel.find(item => item.selected);
            if(this.manageDialogType === 1){
	            //修改返佣比例
	            util.fetch2(`${util.ajaxUrl2}/api/v1/user/manage-downgrade`,{
					uid:this.manageUid,
	                level:selectItem.type==4?0:selectItem.type,
	                rateE2:Number(this.manageRateE2),
	                unlimited:selectItem.type==4?1:0
				}).then(res => {
					Toast(res.code === 0?this.$t('mySetting-key6'):this.errMsg.find(item => item.code === res.code)?this.errMsg.find(item => item.code === res.code)[this.locale]:res.msg || this.$t('noError'));
					//更新本地返佣比例
					if(res.code === 0){
						this.manageDialog = false;
						let rateE2 = Number(this.manageRateE2);
						rateE2 = rateE2 >= 85?85:rateE2;
	                    rateE2 += '%';
	                    let find = this.searchList.find(item => item.uid == this.manageUid);
	                    if(find){
	                    	find.rate = rateE2;
	                    }
					}
					this.btnLoading = res.code === 0?true:false;
					if(!this.manageDialog) this.goSearch(this.manageUid);
				}).catch(e => {
					window.updateError('manage-downgrade:'+window.localStorage.getItem('uid'))
					Toast(this.dialogSystemErr);
				})
			}
			if(this.manageDialogType === 2 && this.manageRemark){
				//提交备注
				this.submitRemark();
			}
        },
		goManage(item,type){
            //点击“管理”按钮
            this.manageUid = item.uid;
            this.manageRemark = item.remark;
            //type  1:管理   2:备注  
            this.manageDialogType = type;
            this.manageDialog = true;
            this.btnLoading = false;
            //初始化弹窗选项到默认
            this.manageRateE2 = item.rate.replace('%','');
            this.manageLevel.map(ele => {
                ele.selected = ele.type == item.rebateLevel?true:false;
                if(item.unlimited === 0){
                    ele.shown = (ele.type === 2 || ele.type===3)?true:false
                }else if(item.unlimited === 1){
                    ele.shown = (ele.type === 2 || ele.type===3)?false:true;
                    //默认选中
                    if(ele.type === 4){
                        ele.selected = true;
                    }
                }
            })
            if(!this.manageLevel.find(item => item.selected)){
                this.manageLevel[0].selected = true;
            }
        },
        goBtnSearch(){
        	//点击“搜索”按钮搜索
        	// if(!this.searchUID) return
        	this.searchList = [];
        	this.goSearch();
        },
        goSearch(uid){
        	// console.log(this.loading)
        	// if(this.loading) return
        	this.search(uid).catch(e => {
        		// 接口异常
        		this.loadError = true;
				this.loading = false;
				this.finished = false;
				this.searchList = [];
        	});
        },
        arrowReset(uid){
        	//当前层级以下箭头归位
        	this.searchList.map(item => {
        		if(item.parentUid == uid){
        			item.hold = true;
        			this.arrowReset(item.uid)
        		}
        	})
        },
        holdChilds(uid){
        	//隐藏当前层级以下全部
        	this.searchList.map(item => {
        		if(item.parentUid == uid){
        			item.shown = false;
        			this.holdChilds(item.uid)
        		}
        	})
        },
        goFold(parentUid,currentUid,shown,hasDown,level,hasSubs){
        	if(hasDown !== 1 || this.loading) return
        	//超过5级，提示去PC查看
        	if(level >= 5){
        		Toast(this.$t('invite-new33'));
        		return
        	}
        	this.searchUID = '';
        	//操作图标方向
        	this.searchList.map(item => {
				if(item.uid == currentUid){
					item.hold = !item.hold;
					if(!item.hold) this.arrowReset(item.uid);
				}
			})
        	let find = this.searchList.find(item => item.parentUid == currentUid);
        	if(find){
        		//已存在数据
        		this.searchList.map(item => {
					if(item.parentUid == currentUid){
						item.shown = !item.shown;
						if(!item.shown){
							this.holdChilds(item.uid)
						}
					}
				})
        	}else{
        		//拉取接口
        		if(hasSubs) this.goSearch(currentUid)
        	}
		},
		async search(uid){
			this.loading = true;
			this.finished = false;
			this.loadError = false;
			let agentUid = uid && typeof uid != 'object'?uid:0;
			if(this.searchUID) agentUid = 0;
			if(this.searchList.filter(item => item.shown).length > 6){
				Toast.loading({
					message: this.$t('loading'),
					forbidClick: true,
					duration:10000
				});
			}
			let _interface = this.isSuperPartner == 1?'agent-list':'friend-list';
			let _params = this.isSuperPartner == 1
				?{
					agent_uid:agentUid,
					product_group:'',
					search:this.searchUID,
					start:'',
					end:'',
					page:1,
					size:10
				}:{
					uid:this.searchUID?this.searchUID:'0',
					page:1,
					size:10
				}
			let _url = `${util.ajaxUrl2}/api/v1/user/${_interface}`;
			axios.get(_url, { params: _params }, { 
				headers: { 
					lang: util.readLang() 
				}
			}).then(xhr => {
				Toast.clear();
				if(xhr && xhr.status === 200){
					let res = xhr.data;
					if(res.code === 0){
						if(res.data && res.data.list && res.data.list.length){
							// this.searchList = res.data.list;
							if(res.data.list.length){
								res.data.list.map(item => {
									item.rate = item.rate >= 85?85:item.rate;
		                            item.rate += '%';
		                            //默认折叠
			                        item.hold = true;
			                        //默认展示
			                        item.shown = true;
			                        //是否拥有下级数据
			                        item.hasSubs = true;
			                        //保存上一层uid
			                        item.parentUid = agentUid;
			                        if(item.level == 0){
			                        	item.shwnLevel = 0;
			                        }else if(item.level == 1){
			                        	item.shwnLevel = this.$t('invite-new34');
			                        }else if(item.level == 2){
			                        	item.shwnLevel = this.$t('invite-new35');
			                        }else if(item.level == 3){
			                        	item.shwnLevel = this.$t('invite-new36');
			                        }else if(item.level == 4){
			                        	item.shwnLevel = this.$t('invite-new37');
			                        }else if(item.level == 5){
			                        	item.shwnLevel = this.$t('invite-new38');
			                        }else if(item.level == 6){
			                        	item.shwnLevel = this.$t('invite-new39');
			                        }
			                        let _time = util.transTime4(item.create_time);
			                        item.showTime = _time[0]+'-'+_time[1]+'-'+_time[2];
			                        item.balance = util.countNum(item.balance,2);
								})
							}
							//整合数据
							if(this.searchList.length === 0 || agentUid==0){
								this.searchList = res.data.list;
							}else{
								let findIndex = this.searchList.findIndex(item => item.uid === agentUid);
								this.searchList.splice(findIndex+1,0,...res.data.list)
							}
						}else{
							// this.searchList = [];
						}
						//若数据为空，则记录缓存
						if(res && res.data && res.data.list && res.data.list.length === 0 && agentUid != this.uid){
							this.searchList.map(item => {
								if(item.uid === agentUid){
									item.hasSubs = false;
								}
							})
						}
						// console.log(this.searchList)
					}else{
						Toast(this.errMsg.find(item => item.code === res.code)?this.errMsg.find(item => item.code === res.code)[this.locale]:res.msg || this.$t('noError'))
					}
					this.finished = true;
					this.loadError = false;
					this.loading = false;
				}else{
					
				}
			}).catch(e => {
				window.updateError(_url+window.localStorage.getItem('uid'))
			})
		},
		selectlevel(_item){
            this.manageLevel.map(item => {
                item.selected = item.level == _item.level?true:false
            })
        },
		share(type){
			util.callHandler('showShareInfo',{
				type,
				shareData: {
        			title: this.$t('invite-key34'),
        			content: this.$t('invite-key35'),
        			url: this.inviteCode?this.getInviteUrl:'',
      			}
			},res => {
				console.log(res)
			})
		},
		selectCountry(item){
			//选择语言
			this.langDialog = !this.langDialog;
			this.inviteLocale = item.code;
			this.createShort();
		},
		createShort(){
			let params = {
                url:this.getInviteUrl
            }
            let md5Key = util.getHashStr(params)
            params['sign'] = md5Key
			util.fetch(`${util.ajaxUrl}/user/short-url`,params).then(res => {
				if(res.retCode === 0){
					this.getInviteUrl2 = res.retData.url;
					window.localStorage.setItem('getInviteUrl2',this.getInviteUrl2)
				}else{
					Toast(res.retMsg || this.$t('noError'))
				}
			}).catch(error => {
				Toast(this.dialogSystemErr);
				console.log(error)
			})
		},
		createInviteCode(){
			//邀请码
			let params = {};
			let md5Key = util.getHashStr(params)
            params['sign'] = md5Key
			util.fetch(`${util.ajaxUrl}/agent/invite-code`,params).then(res => {
				if(res.retCode === 0){
					this.inviteCode = res.retData.invite_code;
					util.setStorage('inviteCode',this.inviteCode);
					this.createShort();
				}else{
					Toast(res.retMsg || res.retHtml || res.retData || this.$t('noError'))
				}
			}).catch(e => {
				Toast(this.dialogSystemErr);
			})
		},
		init(){
			if(window.localStorage.getItem('getInviteUrl2')){
				this.getInviteUrl2 = window.localStorage.getItem('getInviteUrl2');
			}
			//拉取用户信息
			util.fetch(`${util.ajaxUrl}/user/user-info`,{}).then(res => {
				if(res.retCode === 0){
					this.headImg = res.retData.head_img;
					this.accountName = res.retData.nickname;
					this.uid = res.retData.uid;
					window.localStorage.setItem('uid',this.uid);
					this.moneyRate = res.retData.system_rebate_rate_e2;
					this.isSuperPartner = Number(res.retData.is_super_partner);
					this.activeId = this.isSuperPartner===0?4:this.activeId;
					window.localStorage.setItem('isSuperPartner',this.isSuperPartner);
					window.localStorage.setItem('headImg',this.headImg);
					window.localStorage.setItem('accountName',this.accountName);
					window.localStorage.setItem('uid',this.uid);
				}else{
					Toast(res.retMsg || this.$t('noError'))
				}
			}).catch(error => {
				Toast(this.dialogSystemErr);
				console.log(error)
			})
			//拉取余额
			util.fetch(`${util.ajaxUrl}/user/new-balance`,{}).then(res => {
				if(res.retCode === 0){
					try{
						let list = res.retData.commission.list;
						let find = list.find(item => item.symbol === this.currentId);
						if(find){
							this.leftMoney = find.amount
						}
					}catch(e){
						console.log(e)
					}
				}else{
					Toast(res.retMsg || this.$t('noError'))
				}
			}).catch(error => {
				Toast(this.dialogSystemErr);
			})
			//拉取好友人数、子代理人数
			util.fetch2(`${util.ajaxUrl2}/api/v1/index/sketch`,{
				currency:this.currentId
			}).then(res => {
				if(res.code === 0){
					if(res.data && res.data.partnerStat && res.data.partnerStat.length === 2){
						this.subFriends = res.data.partnerStat[0].count;
						this.subAgent = res.data.partnerStat[1].count;
						this.level1RegCountToday = res.data.level1RegCountToday;
					}
				}else{
					Toast(res.msg || this.$t('noError'))
				}
			}).catch(error => {
				window.updateError('sketch:'+window.localStorage.getItem('uid'))
				Toast(this.dialogSystemErr);
			})
		},
		goTransfer(){
			if(this.isSuperPartner==1){
				//跳转到划转页面
				util.callHandler('openUrl',{
					url: 'flutterApp://transferMainPage?from=3',
					title:'',
					needLogin:false,
					popVC:false,		//跳转的时候是否干掉当前页面
	                hiddenNav:false,	//是否全屏
				},res => {
					console.log(res)
				})
			}else{
				this.$router.push({
					path:'/besuper'
				})
			}
		},
		copyText(code){
			//复制邀请码
			this.$copyText(code).then(() => {
				Toast(this.$t('copySuccess'))
			}).catch(() => {
				Toast(this.$t('copyFailed'))
			})
		},
		goBack(){
			if(!this.isShowNav) return
			util.navigateBack(-1,this)
		},
		clicRight(){
			if(this.wait){
				let dialogDebug = window.localStorage.getItem('dialogDebug');
				if(dialogDebug && dialogDebug==='1'){
					//清除悬浮窗
					window.localStorage.removeItem('dialogDebug')
				}else{
					//设定悬浮窗
					window.localStorage.setItem('dialogDebug','1')
				}
			}
		},
		clickLeft(){
			this.wait = true;
			setTimeout(()=>{
				this.wait = false;
			},1000)
		},
	},
	mounted(){
		if(this.$refs && this.$refs.scroll){
			this.$refs.scroll.onscroll = res => {
				this.distance = res.target.scrollLeft;
				this.distanceTop = res.target.scrollTop;
			}
		}
	},
	created() {
		//若中文版，则直接显示空白提示文字
		if(this.locale === 'zh'){
			document.querySelector('#bbj').innerHTML = '<p style="padding:20px;text-align:center;">暂无数据</p>';
			return 
		}
		this.manageLevel.find(item => item.type === 2).level = this.$t('invite-new22');
		this.manageLevel.find(item => item.type === 3).level = this.$t('invite-new23');
		this.manageLevel.find(item => item.type === 4).level = this.$t('invite-new24');
		//若存在缓存，则优先渲染缓存
		if(util.getStorage('inviteCode')) this.inviteCode = util.getStorage('inviteCode');
		util.waitSDKReady().then(token => {
			this.token = token;
			this.sketchList(null,null,1);
			this.inviteLocale = this.locale;
			this.init();
			//判断是否隐藏顶部导航栏
			if(this.$route.query.versionCode){
				let versionCode = Number(this.$route.query.versionCode);
				if(versionCode >= 408){
					this.isShowNav = false;
				}
			}
		}).catch((e) => {
			console.log('获取token失败')
		})
		setTimeout(()=>{
			util.registerHandler('refreshCommonRequestWhenGoBackView',res => {
				//再次进入页面的时候刷新数据
				if(this.token) this.init();
				util.callHandler('setStatusBarStyle',{
					style:'light'
				})
			})
			//退出登录的时候native调用H5方法清除token缓存
			util.registerHandler('loginOutDeleteToken',res => {
				this.token = '';
				localStorage.removeItem('token');
			})
			util.callHandler('setStatusBarStyle',{
				style:'light'
			})
		},500)
    }
}